package cn.legend.travel.admin.authorize.controller;

import cn.legend.travel.admin.authorize.pojo.param.UserAddNewParam;
import cn.legend.travel.admin.authorize.pojo.param.UserLoginParam;
import cn.legend.travel.admin.authorize.pojo.param.UserUpdateParam;
import cn.legend.travel.admin.authorize.service.IUserService;
import cn.legend.travel.common.pojo.authentication.CurrentPrincipal;
import cn.legend.travel.common.web.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.hibernate.validator.constraints.Range;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.Size;

@Api(tags = "管理员账户管理模块")
@Validated
@RestController
@RequestMapping("users")
@RequiredArgsConstructor
public class UserController {
    private final IUserService service;

    @PostMapping("/login")
    @ApiOperation("登录功能")
    public JsonResult login(@RequestBody UserLoginParam param) {
        return JsonResult.ok(service.login(param));
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    public JsonResult logout(@ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal) {
        service.logout(principal);
        return JsonResult.ok();
    }

    @PostMapping("/update-password")
    @ApiOperation("修改密码")
    public JsonResult updatePassword(@RequestParam @Size(min = 8, message = "密码长度不得小于8") String newPwd, @ApiIgnore @AuthenticationPrincipal CurrentPrincipal principal) {
        service.updatePassword(newPwd, principal.getId());
        return JsonResult.ok();
    }

    @GetMapping("/getUserList")
    @ApiOperation("获取管理员列表")
    @PreAuthorize("hasAuthority('/users/getUserList')")
    public JsonResult getList(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        return JsonResult.ok(service.getUserList(pageNum));
    }

    @PostMapping("/addNew")
    @ApiOperation("新增管理员")
    @PreAuthorize("hasAuthority('/users/addNew')")
    public JsonResult addNew(@RequestBody UserAddNewParam param) {
        service.addNew(param);
        return JsonResult.ok();
    }

    @PostMapping("/update")
    @ApiOperation("编辑管理员")
    @PreAuthorize("hasAuthority('/users/update')")
    public JsonResult update(@RequestBody @Validated UserUpdateParam param) {
        service.update(param);
        return JsonResult.ok();
    }

    @PostMapping("/delete")
    @ApiOperation("删除管理员")
    @PreAuthorize("hasAuthority('/users/delete')")
    public JsonResult delete(@RequestParam("id") @Range(min = 2, message = "id为1的用户不允许删除") Long id) {
        service.deleteById(id);
        return JsonResult.ok();
    }
}
